import axios from 'axios'
import {ElMessage, ElMessageBox} from 'element-plus'
import {downloadContentType, previewContentType} from '~/utils/index'

const baseURL = (import.meta.env.VITE_BASE_URL as string)
const service = axios.create({
    baseURL: baseURL,
    timeout: 50000
})

service.interceptors.request.use(
    config => {
        const token = localStorage.getItem("token")
        if (token) {
            config.headers['token'] = token
        }
        return config
    },
    error => {
        console.log(error)
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    (response): any => {
        const res: any = response.data
        if (downloadContentType.indexOf(response.headers['content-type']) >= 0) {
            // @ts-ignore
            let {fileName} = response.config.params ? response.config.params : {}
            const url = window.URL.createObjectURL(res)
            const link = document.createElement('a')
            link.style.display = 'none' // 设置隐藏创建的标签
            link.href = url
            if (!fileName) {
                fileName = /(;filename=)+[^]+/g.exec(
                    response.headers['content-disposition']
                )
                fileName = fileName ? decodeURI(fileName[0].substr(10)) : '未知'
            }
            link.setAttribute('download', fileName) // 下载文件名称
            document.body.appendChild(link)
            link.click() // 点击下载
            link.remove() // 下载后移除
            window.URL.revokeObjectURL(link.href) // 用完之后使用URL.revokeObjectURL()释放；
            return null
        } else if (previewContentType.indexOf(response.headers['content-type']) >= 0) {
            return res
        }
        // if the custom code is not 200, it is judged as an error.
        if (res.code !== 200) {
            // 坏的凭证 重新授权
            if (res.code === 302) {
                // to re-login
                ElMessageBox.confirm(
                    '您已注销，可以取消以停留在此页面，或重新登录',
                    '确认注销',
                    {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).then(() => {
                    localStorage.removeItem("token")
                    window.location.href = "/login"
                }).catch((e) => {
                    console.log(e)
                })
            } else {
                ElMessage({
                    message: res.message || 'Error',
                    type: 'error',
                    duration: 5 * 1000
                })
            }
            return res
        }
        return res
    },
    error => {
        console.log('err' + error) // for debug
        ElMessage({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default service
